package com.zllkj.mm.module.home.fragments;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.cx.base.BaseDialog;
import com.example.bajian.sheetdialogue.SheetDialog;
import com.foamtrace.photopicker.ImageCaptureManager;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;
import com.zllkj.mm.R;
import com.zllkj.mm.api.net.HttpManager;
import com.zllkj.mm.api.net.HttpOnNextListener;
import com.zllkj.mm.api.net.ProgressSubscriber_net;
import com.zllkj.mm.api.net.UploadPost;
import com.zllkj.mm.api.network.RetrofitHelper;
import com.zllkj.mm.api.network.RxHelper;
import com.zllkj.mm.api.network.subscriber.BaseRxSubscriber;
import com.zllkj.mm.api.network.subscriber.BaseString;
import com.zllkj.mm.api.network.subscriber.ProgressSubscriber;
import com.zllkj.mm.base.BaseTitleFragment;
import com.zllkj.mm.common.L;
import com.zllkj.mm.model.entity.UserSelfVo;
import com.zllkj.mm.module.UIHelper;
import com.zllkj.mm.module.general.fragments.LoginFragment2;
import com.zllkj.mm.module.main.MainActivity;
import com.zllkj.mm.module.main.fragments.MineFragment;
import com.zllkj.mm.util.CircleImageView;
import com.zllkj.mm.util.EmptyUtils;
import com.zllkj.mm.util.ImageUtils;
import com.zllkj.mm.util.KLog;
import com.zllkj.mm.widgets.AddressDialog;
import com.zllkj.mm.widgets.DateDialog;
import com.zllkj.mm.widgets.MenuDialog;
import com.zllkj.mm.widgets.SettingBar;

import org.json.JSONArray;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.http.Url;
import top.zibin.luban.Luban;

import static android.app.Activity.RESULT_OK;
import static com.zllkj.mm.widgets.AutoScrollTextView.TAG;

/**
 * Created by leon_ok.
 */

public class EditInfoFragment extends BaseTitleFragment {

    UserSelfVo userInfo;
    private String mProvince = "";
    private String mCity = "";
    private String mArea = "";
    private String birthday = "";
    String userLogo;
    SheetDialog sheetDialog;
    String path;
    Disposable disposable;
    /**
    拍照使用的Uri
     */
    Uri  photoUri;
    @BindView(R.id.headPortraitIv)
    com.zllkj.mm.util.CircleImageView headPortraitIv;
    @BindView(R.id.sbIv)
    SettingBar sbIv;
    @BindView(R.id.etName)
    EditText etName;
    @BindView(R.id.tvSex)
    TextView tvSex;
    @BindView(R.id.rb1)
    RadioButton rb1;
    @BindView(R.id.rb2)
    RadioButton rb2;
    @BindView(R.id.rg)
    RadioGroup rg;
    @BindView(R.id.tvBirthday)
    TextView tvBirthday;
    @BindView(R.id.tvSSQ)
    TextView tvSSQ;
    @BindView(R.id.etPhone)
    EditText etPhone;
    @BindView(R.id.etDes)
    EditText etDes;
    @BindView(R.id.confirm)
    View confirm;
    @BindView(R.id.llRoot)
    LinearLayout llRoot;
    @BindView(R.id.llSex)
    View llSex;
    @BindView(R.id.etSex)
    EditText etSex;

    public static EditInfoFragment newInstance() {
        return new EditInfoFragment();
    }
    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_editinfo;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        if (null != LoginFragment2.loginS &&0==LoginFragment2.loginS.ifPerfectSelfInfo) {
            setCommonTitle("完善资料");
        }else{
            setCommonTitle("编辑资料").setShowImgLeft(false).setRightBtn("取消", view -> removeFragment());
            getDefaultData();
        }
        llSex.setVisibility(View.GONE);
    }

    @OnClick({R.id.etSex,R.id.civ, R.id.ivEdit, R.id.tvSex, R.id.llBirthday, R.id.llSSQ, R.id.confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.civ:
            case R.id.ivEdit:
                openImageChooserActivity();
                break;
            case R.id.tvSex:
            case R.id.etSex:
                showSexDialog();
                break;
            case R.id.llBirthday:
                showBirthdayDialog();
                break;
            case R.id.llSSQ:
                showSelectCityDialog();
                break;
            case R.id.confirm:
                if (TextUtils.isEmpty(etName.getText().toString())) {
                    L.showToast("昵称不能为空");
                    return;
                }
                confirmData();
                break;
        }
    }

    /**
     * 获取历史数据
     */
    private void getDefaultData() {
        addSubscribe(RetrofitHelper.getInstance().getApi()
                        .getInfo(L.sign(L.sign(new HashMap())))
                        .compose(RxHelper.<UserSelfVo>defaultHandleResult())
                        .subscribe(new BaseRxSubscriber<UserSelfVo>() {
                            @Override
                            protected void onSucc(UserSelfVo o) {
                                MineFragment.userInfo = o;
                                userInfo = o;
                                L.setImg(o.userLogo, headPortraitIv);
                                etName.setText(o.nikeName);
                                if (o.sex != 3) {
                                    ((RadioButton) rg.getChildAt(o.sex == 1 ? 0 : 1)).setChecked(true);
                                }
                                etSex.setHint(o.sex == 1 ? "男" : o.sex == 2 ? "女" : "保密");
                                tvBirthday.setText(o.birthday);
                                mProvince = o.province;
                                mCity = o.city;
//                              mArea = o.district;
                                tvSSQ.setText(o.province + " " + o.city/* + " " + o.district*/);
                                etPhone.setText(o.phone);
                                etDes.setText(o.intro);
                            }
                        })
        );
    }

    /**
     * 提交数据到服务器
     */
   private void confirmData() {
       addSubscribe(RetrofitHelper.getInstance().getApi()
                       .userEdit(L.sign(new HashMap() {{
                           put("birthday", !EmptyUtils.isEmpty(birthday) ? birthday : userInfo.birthday);
                           put("province", mProvince);
                           put("city", mCity);
                           put("nikeName", etName.getText().toString());
                           put("sex", rb1.isChecked() ? 1 : rb2.isChecked() ? 2 : 3);
                           put("intro", etDes.getText().toString());
                           put("userLogo", !EmptyUtils.isEmpty(userLogo) ? userLogo : userInfo.userLogo);
                       }}))
                       .compose(RxHelper.<UserSelfVo>defaultHandleResult())
                       .subscribe(new ProgressSubscriber<UserSelfVo>(getContext()) {
                           @Override
                           protected void onSucc(UserSelfVo o) {
                               L.showToast("保存成功");
                               // removeFragment();
                               UIHelper.showMainPage(getActivity());
                           }
                       })
       );
    }

    private void showBirthdayDialog(){
       new DateDialog.Builder(getContext())
               .setTitle(getString(R.string.date_title))
               // 确定按钮文本
               .setConfirm(getString(R.string.common_confirm))
               // 设置 null 表示不显示取消按钮
               .setCancel(getString(R.string.common_cancel))
               // 设置日期
               //.setDate("2018-12-31")
               //.setDate("20181231")
               //.setDate(1546263036137)
               // 设置年份
               //.setYear(2018)
               // 设置月份
               //.setMonth(2)
               // 设置天数
               //.setDay(20)
               // 不选择天数
               //.setIgnoreDay()
               .setListener(new DateDialog.OnListener() {
                   @Override
                   public void onSelected(com.zllkj.mm.widgets.BaseDialog dialog, int year, int month, int day) {
//                                toast(year + getString(R.string.common_year) + month + getString(R.string.common_month) + day + getString(R.string.common_day));

                       // 如果不指定时分秒则默认为现在的时间
                       Calendar calendar = Calendar.getInstance();
                       calendar.set(Calendar.YEAR, year);
                       // 月份从零开始，所以需要减 1
                       calendar.set(Calendar.MONTH, month - 1);
                       calendar.set(Calendar.DAY_OF_MONTH, day);
//                                toast("时间戳：" + calendar.getTimeInMillis());
                       birthday = new SimpleDateFormat("yyyy年MM月dd日").format(calendar.getTime());
                       tvBirthday.setText(birthday);
                   }

                   @Override
                   public void onCancel(com.zllkj.mm.widgets.BaseDialog dialog) {
                   }
               })
               .show();
    }

    /**
     * 选择省市区
     */
     private void showSelectCityDialog() {
         new AddressDialog.Builder(getContext())
                 //.setTitle("选择地区")
                 // 设置默认省份
//                        .setProvince(mProvince)
                 // 设置默认城市（必须要先设置默认省份）
//                        .setCity(mCity)
                 // 不选择县级区域
                 .setIgnoreArea()
                 .setListener((dialog, province, city, area) -> {
                     mProvince = province;
                     mCity = city;
//                            mArea = area;
                     tvSSQ.setText(province + " " + city /*+ " " + area*/);
                 })
                 .show();
    }

    /**
     * 相册选取或拍照
     */
    private void openImageChooserActivity() {
        sheetDialog = new SheetDialog(getActivity())
                .setTitle("请选择：")
                .setCanceledOnTouchOutside(false)
                .addSheetItems(new String[]{"相册", "拍照"}
                        , SheetDialog.SheetItemColor.Blue, which -> {
                            switch (which) {
                                case 1:
                                  getActivity().startActivityForResult(new Intent(Intent.ACTION_PICK).setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"), 102);

                                    break;
                                case 2:
                                    if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA)
                                            != PackageManager.PERMISSION_GRANTED) {
                                        ActivityCompat.requestPermissions(getActivity()
                                                , new String[]{Manifest.permission.CAMERA,
                                                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
                                        return;
                                    }

                                    takePhoto();

//                                    path = Environment.getExternalStoragePublicDirectory(
//                                            Environment.DIRECTORY_PICTURES).getAbsolutePath() +
//                                            File.separator + "mmImg.jpg";
//                                    Intent takePictureIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                                    if (takePictureIntent.resolveActivity(getContext().getPackageManager())!=null){
//                                        File photoFile=createImageFile();
//                                        if (photoFile!=null){
//                                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
//                                                    Uri.fromFile(photoFile));
//                                        }
//                                    }
//                                    getActivity().startActivityForResult(takePictureIntent,101);

//                                    getActivity().startActivityForResult(
//                                            new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
//                                                    .putExtra(MediaStore.EXTRA_OUTPUT,
//                                                            Uri.fromFile(new File(path))), 101);
                                    break;
                            }
                        }
                )
                .show()
        ;
    }


    void takePhoto1(){
        /**
         * 最后一个参数是文件夹的名称，可以随便起
         */
        File file=new File(Environment.getExternalStorageDirectory(),"拍照");
        if(!file.exists()){ file.mkdir(); }
        /**
         * 这里将时间作为不同照片的名称
         */
       //File output=new File(file,System.currentTimeMillis()+".jpg");
        File output=new File(file,System.currentTimeMillis()+".jpg");
        /**
         * 如果该文件夹已经存在，则删除它，否则创建一个
         */
        try { if (output.exists()) { output.delete(); }
            output.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 隐式打开拍照的Activity，并且传入CROP_PHOTO常量作为拍照结束后回调的标志
         * 将文件转化为uri
         */
        photoUri = Uri.fromFile(output);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(intent, 101);
    }

    /**
     * 拍照获取图片
     */
    private void takePhoto() {
        //执行拍照前，应该先判断SD卡是否存在
        String SDState = Environment.getExternalStorageState();
        if(SDState.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//"android.media.action.IMAGE_CAPTURE"
            /***
             * 需要说明一下，以下操作使用照相机拍照，拍照后的图片会存放在相册中的
             * 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
             * 如果不实用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
             */
            ContentValues values = new ContentValues();
            photoUri = getContext().getContentResolver().
                    insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(intent, 101);
        }else{
            Toast.makeText(getContext(),"内存卡不存在", Toast.LENGTH_LONG).show();
        }
    }

    private File createImageFile() {
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File image = null;
        try {
            image = File.createTempFile(
                    generateFileName(),  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        //mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    public static String generateFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        return imageFileName;
    }

    @Override
    public void onActivityResult(final int requestCode, int resultCode, final Intent data) {

        KLog.e("onActivityResult() called with: requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");

        if (requestCode == 101 && resultCode == RESULT_OK) {
//            if (data != null) { //当没有指定外部存储路径时为缩略图模式,意图中直接携带了缩略图
//              //  headPortraitIv.setImageBitmap(((Bitmap) data.getExtras().get("data")));
//                headPortraitIv.setImageBitmap(BitmapFactory.decodeFile(data.getData().getPath()));
//
//            } else { //当指定路径,意图不再携带数据,用户自行读取文件并显示
//                headPortraitIv.setImageBitmap(BitmapFactory.decodeFile(path));
//            }
            try {
                /**
                 * 该uri就是照片文件夹对应的uri
                 */
               // Bitmap bit = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(photoUri));
               // headPortraitIv.setImageBitmap(bit);

//                FileInputStream fis = new FileInputStream(getPathFromUri(getContext(),photoUri));
//                Bitmap bitmap  = BitmapFactory.decodeStream(fis);
//                 headPortraitIv.setImageBitmap(bitmap);

//                String string= getRealPathFromURI(getContext(),photoUri);
//                Glide.with(getContext()).load(photoUri) .thumbnail( 0.2f )
//                        .into( headPortraitIv );
                // 加载SD卡根目录的test.jpg 图片
               // String path = "file://"+ getPathFromUri(getContext(),photoUri);

//                File file = new File(getRealPathFromURI(getContext(),photoUri));
//                Glide.with(getContext())
//                        .load(file)
//                        .into(headPortraitIv);
                String path = "file://"+ getPathFromUri(getContext(),photoUri);
                Glide.with(getContext())
                        .load(path)
                        .into(headPortraitIv);


            } catch (Exception e) {
                Toast.makeText(getContext(),"读取失败",Toast.LENGTH_SHORT).show();
            }


        }//RESULT_CANCELED

        if (resultCode == RESULT_OK && (requestCode == 101 || requestCode == 102)) {
            if (data != null) {
                try {
                    Bitmap bit = BitmapFactory.decodeStream(
                            getActivity().getContentResolver().openInputStream(
                                   data.getData()));
                    headPortraitIv.setImageBitmap(bit);
                }catch (Exception e){
                    Toast.makeText(getActivity(),e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            // Uri uri  =data.getData();
            //String string= getRealPathFromURI(getContext(),uri);
//                Glide.with(getContext()).load(uri) .thumbnail( 0.2f )
//                        .into( headPortraitIv );;
               // headPortraitIv.setImageBitmap(BitmapFactory.decodeFile(data.getData().getPath()));
            } else {
//                Bitmap bitmap = ImageUtils.getBitmap(fileUrl, 540, 960);
//                ImageUtils.writeBitmap(this, bitmap, dirPath, "yinhangka-1.png", Bitmap.CompressFormat.PNG);
//                headPortraitIv.setImageBitmap(bitmap);

            }

            final File file = new File(requestCode == 101 ? path : ImageUtils.getImageAbsolutePath(getActivity(), data.getData()));

            disposable = Flowable.just(new ArrayList<String>() {{
                add(requestCode == 101 ? path : ImageUtils.getImageAbsolutePath((getActivity()), data.getData()));
            }})
                    .observeOn(Schedulers.io())
                    .map(new Function<List<String>, List<File>>() {
                        @Override
                        public List<File> apply(@NonNull List<String> list) throws Exception {
                            return Luban.with(getActivity()).load(list).setFocusAlpha(false).get();
//                            return new ArrayList<File>() {{
//                                add(file);
//                            }};
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<List<File>>() {
                        @Override
                        public void accept(List<File> files) {
                            KLog.e(files);
                            ProgressDialog progressDialog = new ProgressDialog(getContext());
                            progressDialog.show();
                            HttpManager.getInstance().doHttpDeal(new UploadPost(new ProgressSubscriber_net(new HttpOnNextListener<BaseString>() {
                                @Override
                                public void onNext(final BaseString baseString) {
                                    progressDialog.dismiss();
                                    userLogo = baseString.string;
                                 //   L.setImg(userLogo, headPortraitIv);
                                }
                            }, getActivity(), true, false) {
                                @Override
                                public void onCancelProgress() {
                                    super.onCancelProgress();
                                    progressDialog.dismiss();
                                }
                            }, RequestBody.create(MediaType.parse("multipart/form-data"), /*file*/files.get(0))));
                        }
                    });


        }
        if (resultCode == RESULT_OK && requestCode == 80) {
            if (data != null) {
                headPortraitIv.setImageBitmap(((Bitmap) data.getExtras().get("data")));
            } else {
//                Bitmap bitmap = ImageUtils.getBitmap(fileUrl, 540, 960);
//                ImageUtils.writeBitmap(this, bitmap, dirPath, "yinhangka-1.png", Bitmap.CompressFormat.PNG);
//                headPortraitIv.setImageBitmap(bitmap);
            }

//            HttpManager.getInstance().doHttpDeal(new UploadPost(new ProgressSubscriber(new HttpOnNextListener<BaseString>() {
//                @Override
//                public void onNext(final BaseString baseString) {
////                    try {
////                        new File(dirPath + "yinhangka-1.png").delete();
////                    } catch (Exception e) {
////                        e.printStackTrace();
////                    }
//
////                    r(new Runnable() {
////                        @Override
////                        public void run() {
////                            Cocos2dxJavascriptJavaBridge.evalString("cc.anysdkMgr.showAlbumCallback('" + baseString.string + "')");
////                        }
////                    });
//                    String a = baseString.string;
//                    String method = "javascript:payImageCallback(\"" + a + "\")";
//                    mWebView.loadUrl(method);
//                }
//            }, getActivity(), true, false) {
//                @Override
//                protected void onSucc(Object o) {
//
//                }
//
//                @Override
//                public void onCancelProgress() {
//                    super.onCancelProgress();
//                }
//            }, RequestBody.create(MediaType.parse("multipart/form-data"), new File(ImageUtils.getImageAbsolutePath(getActivity(), data.getData())))));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @SuppressLint("NewApi")
    public static String getPathFromUri(final Context context, final Uri uri) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
                && DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) { //ExternalStorageProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(uri)) { //DownloadsProvider
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) { //MediaProvider
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = { column };
        try {
            cursor = context.getContentResolver()
                    .query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }


    @Override
    public void onResume() {
        super.onResume();
        if (null != sheetDialog) {
            sheetDialog.dismiss();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != disposable) {
            disposable.dispose();
        }
    }


    /**
     * 显示选择性别的对话框
     */
    private void showSexDialog() {
        List<String> data = new ArrayList<>();
        data.add("男");
        data.add("女");
        // 底部选择框
        new MenuDialog.Builder(getContext())
                // 设置 null 表示不显示取消按钮
                //.setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                //.setAutoDismiss(false)
                .setList(data)
                .setListener(new MenuDialog.OnListener<String>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, String string) {
                        ((RadioButton) rg.getChildAt(position)).setChecked(true);
                        etSex.setHint(position + 1 == 1 ? "男" : "女");
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                    }
                })
                .show();
    }

    public static String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

        finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }


}
